package openglsuperbible.Chapter6;

import openglsuperbible.glutils.*;
import org.lwjgl.LWJGLException;
import org.lwjgl.Sys;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import static org.lwjgl.opengl.GL11.*;

/**
 *
 * @author Matthew
 */
public class ADSPhong {
        public static final int DISPLAY_HEIGHT = 600;
        public static final int DISPLAY_WIDTH = 800;

        public long lastFrame;
       
        private Shader shader;
        
        private MatrixStack modelViewMatrix;  // Modelview Matrix
        private MatrixStack projectionMatrix; // Projection Matrix
        private GLFrustrum frustrum;    // View Frustum
        private GeometryTransform transformPipeline; // Geometry Transform Pipeline
        private GLFrame cameraFrame;
        private GLBatch sphere;

        private float angle = 0.0f;
	private float vEyeLight[] = { -100.0f, 100.0f, 100.0f };
	private float vAmbientColor[] = { 0.1f, 0.1f, 0.1f, 1.0f };
	private float vDiffuseColor[] = { 0.0f, 0.0f, 1.0f, 1.0f };
//	private float vSpecularColor[] = { 1.0f, 1.0f, 1.0f, 1.0f };
        
        
        public void initGL()
        {
            // Black background
            glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
            shader = new Shader("ADSPhong","ADSPhong"); 
             
            glEnable(GL_DEPTH_TEST);
            glEnable(GL_CULL_FACE);
//	    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
            
            frustrum = new GLFrustrum();               
            modelViewMatrix = new MatrixStack();
            cameraFrame = new GLFrame();
            sphere = GLBatchFactory.makeSphere(1.0f, 26, 13); 

        }
        
              
       

    void render()
    {    
           angle+= 0.05f * getDelta();  
    
	// Clear the window with current clearing color
	 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
         modelViewMatrix.push();
         float[] mCamera = cameraFrame.getCameraMatrix();
         modelViewMatrix.multiply4(mCamera);
         
         modelViewMatrix.translate(0, 0, -4.0f);
         modelViewMatrix.rotate(angle, 0.0f, 1.0f, 0.0f);   

        shader.use();

        shader.setUniformMatrix4("mvpMatrix", transformPipeline.getModelViewProjectionMatrix()); 
        shader.setUniformMatrix4("mvMatrix",  transformPipeline.getModelViewMatrix());
        shader.setUniformMatrix3("normalMatrix",transformPipeline.getNormalMatrix());
        shader.setUniform4("ambientColor",vAmbientColor);
        //shader.setUniform4("specularColor",vSpecularColor);
        shader.setUniform4("diffuseColor",vDiffuseColor);
        shader.setUniform3("vLightPosition",vEyeLight);
        sphere.draw(shader.getAttributeLocations());     

        modelViewMatrix.pop();

	// Flush drawing commands
	Display.update();  
    }
        
       public void create() throws LWJGLException { 
            //Display    
            Display.setDisplayModeAndFullscreen(new DisplayMode(DISPLAY_WIDTH,DISPLAY_HEIGHT)); 
            
            Display.setTitle("ADS Lighting, Phong Shading");
            Display.create();
            
            //Keyboard         
            Keyboard.create();   
            //Mouse          
            Mouse.setGrabbed(false);
            Mouse.create();  
            //OpenGL      
            initGL();    
            resizeGL();  
        }  
       
        public void resizeGL() {   
            glViewport(0,0,DISPLAY_WIDTH ,DISPLAY_HEIGHT);
            frustrum.setPerspective(35f, Display.getWidth()/ Display.getHeight(),1.0f, 100.0f);
            projectionMatrix = new MatrixStack(frustrum.getProjectionMatrix());
            // Set the transformation pipeline to use the two matrix stacks 
            transformPipeline = new GeometryTransform(modelViewMatrix, projectionMatrix);
        } 
       
            public void destroy() {  
                //Methods already check if created before destroying.  
                Mouse.destroy();   
                Keyboard.destroy();
                Display.destroy();     
            } 
        
            public static void main(String[] args) {
            ADSPhong main = null;
            try { 
                 main = new ADSPhong(); 
                main.create(); 
                main.run();
            }          
            catch(Exception ex) {  
                 
            }          
            finally { 
                if(main != null) {  
                    main.destroy();
                }         
            }      
        } 
            
            public void run() 
            {
                while (!Display.isCloseRequested() && !Keyboard.isKeyDown(Keyboard.KEY_ESCAPE)) {              
                       
                render();
       
             
                Display.sync(60);
                Display.setVSyncEnabled(true); 
                
                }
            }
                        
                            	/** 
	 * Calculate how many milliseconds have passed 
	 * since last frame.
	 * 
	 * @return milliseconds passed since last frame 
	 */
	public int getDelta() {
	    long time = getTime();
	    int delta = (int) (time - lastFrame);
	    lastFrame = time;
	 
	    return delta;
	}
	
	/**
	 * Get the accurate system time
	 * 
	 * @return The system time in milliseconds
	 */
	public long getTime() {
	    return (Sys.getTime() * 1000) / Sys.getTimerResolution();
	}
        
}
